package com.huasheng.infohub.actions;

import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
//import org.apache.struts2.interceptor.ServletResponseAware;

import com.huasheng.infohub.dao.UserInfoDao;
import com.huasheng.infohub.dao.impl.UserInfoDaoMysql;
import com.huasheng.infohub.model.UserInfo;

public class UserSigninAction extends BaseAction implements ServletRequestAware/*, ServletResponseAware*/{
	private static final long serialVersionUID = 5338509234535496095L;
	//static private Logger log = Logger.getLogger(UserSigninAction.class);
	
	private UserInfo userinfo;	
	private UserInfoDao userdao = new UserInfoDaoMysql();
	private HttpServletRequest request;
	//private HttpServletResponse response;
	
	public String add() {
		if(userinfo==null || !userinfo.validUserInfo()) {
			return ERROR;
		}
		
		userinfo = userdao.save(userinfo);
		
		keepUserInfoInSession(userinfo);
		
		return userinfo!=null ? SUCCESS : ERROR;
	}
	
	public String login() {
		if(userinfo==null || !userinfo.validUserInfo()) {
			return ERROR;
		}
		
		UserInfo userinfoInDB = userdao.getUserInfo(userinfo.getUser());	
		
		if(userinfoInDB!=null && userinfo.getPassword().equals(userinfoInDB.getPassword())) {
			keepUserInfoInSession(userinfoInDB);
			return SUCCESS;
		} else {
			return ERROR;
		}
	}
	
	public String logout() {
		removeUserInfoInSession();
		
		return SUCCESS;
	}

	public UserInfo getUserinfo() {
		return userinfo;
	}

	public void setUserinfo(UserInfo userinfo) {
		this.userinfo = userinfo;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;		
	}

	/*@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}*/
	
	private void keepUserInfoInSession(UserInfo userinfo){
		if(userinfo!=null) {
			HttpSession session = request.getSession();
			session.setAttribute(USER_INFO, userinfo.getUser());
			session.setMaxInactiveInterval(30*60);
		}
	}
	
	private void removeUserInfoInSession() {
		HttpSession session = request.getSession();
		session.invalidate();
	}
}